import query from './atom/db/query';
import count from './atom/db/count';

declare const action_id: string;
declare const session_id: string;
declare const spaceid: string;

interface Message {
	criteria: object,
	page_size: number,
	page_no: number,
	asc?: string[],
	desc?: string[]
}

function format(d: number) {
	const dt = new Date(d);
	return dt.getFullYear() + '-' + (((dt.getMonth() + 1) < 10) ? ('0' + (dt.getMonth() + 1)) : (dt.getMonth() + 1)) + '-' + ((dt.getDate() < 10) ? ('0' + (dt.getDate())) : (dt.getDate()));
}

async function atom(msg: Message) {
	const systemid = '5981';
	const q = query(action_id, session_id, spaceid, systemid);
	q.prepare('arrange_exam_room', ['_id', 'exam_id', 'exam_subjects_id', 'exam_name', 'exam_subjects_name', 'exam_data', 'exam_date_id', 'layout_no', 'time_quantum_type', 'time_quantum', 'duration', 'exam_no'], msg.criteria, msg.page_size, msg.page_no, msg.asc, msg.desc);
	const t = await q.exec();



	const p = query(action_id, session_id, spaceid, systemid);
	p.prepare('exam_subjects', ['_id', 'exam_subjects_id', 'exam_subjects_name', 'exam_id', 'exam_name', 'fzno', 'course_duration', 'grade', 'total_people', 'department_no', 'department', 'class_name', 'class_id', 'major'], msg.criteria, msg.page_size, msg.page_no, msg.asc, msg.desc);
	const d = await p.exec();


	const a = query(action_id, session_id, spaceid, systemid);
	a.prepare('exam_room_date', ['exam_date_id', 'max_intake_capacity'], msg.criteria, msg.page_size, msg.page_no, msg.asc, msg.desc);
	const b = await a.exec();



	const res = t[0].map((i: any) => {
		const _p = d[0].filter((j: any) => {
			return j.exam_subjects_id === i.exam_subjects_id
		});
		i['exam_data_str'] = format(i['exam_data']);
		return Object.assign(i, _p[0]);
	});
	const ret = res.map((i: any) => {
		const _p = b[0].filter((j: any) => {
			return j.exam_date_id === i.exam_date_id
		});
		return Object.assign(i, _p[0]);
	});

	return ret;
}
